const express = require('express');

const mysql = require('mysql2');

// 创建数据库连接池
const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  database: 'ecut',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
}).promise(); // 注意这里已经调用了 promise 函数


const router = express.Router();

// GET `/user/sign/in`
router.get('/user/sign/in',(req,resp)=>{
    console.log( '即将打开登录页面' );
    console.log( 'cookie: ', req.headers.cookie );
    const session = req.session;
    console.log( session );
    // 从会话对象中获取相关数据并设置到一个新的对象中
    let localeVariables = {
        username: session.username ,
        usernameMessage: session.usernameMessage ,
        passwordMessage: session.passwordMessage ,
        message: session.message 
    }
    // 删除会话对象中的数据
    delete session.username;
    delete session.usernameMessage;
    delete session.passwordMessage;
    delete session.message;

    // '/views/' + `user/sign-in` + '.njk'
    resp.render('user/sign-in' , localeVariables );
});

// POST `/user/sign/in`
router.post('/user/sign/in',(req,resp,next)=>{
    console.log( '数据校验' );
    const session = req.session;
    let { username , password } = req.body ;
    if( !username ) {
        session.usernameMessage = '登录名称不能为空';
        resp.redirect('/user/sign/in');
        return;
    }
    if( !password ) {
        session.username = username ;
        session.passwordMessage = '登录密码不能为空' ;
        resp.redirect('/user/sign/in');
        return;
    }
    // 若 username 和 password 都通过数据校验则执行下一个中间件
    next();
} , (req,resp,next)=>{
    console.log( '与数据库中对比' );
    const session = req.session;
    let { username , password } = req.body ;
    // 编写查询语句
    let sql = 'SELECT id, username, password , nickname FROM t_customers WHERE username = ? ';
    // 指定 SQL 语句中各个参数占位符的取值 (以用户输入的 username 为 account 来实现登录)
    let values = [ username ];
    pool.query( sql , values )
        .then( ([rows,fields]) => {
            let user = rows[0];
            if( user ) {
                // 如果数据库中存储的密码与用户输入的密码不同
                if( user.password != password ){
                    session.username = username ;
                    session.passwordMessage = '登录密码错误' ;
                    resp.redirect('/user/sign/in');
                    return;
                }
                // 将 从数据库查询到的 user 添加到 req 对象中以便于下一个中间件使用
                req.loginUser = user ;
                // 若用户名和密码都正确，则准予登录 (调用下一个中间件实现)
                next();
                return ;
            }
            session.username = username ;
            session.usernameMessage = '登录名称错误' ;
            resp.redirect('/user/sign/in');
        }).catch( reason => {
            session.username = username ;
            session.message = reason ;
            resp.redirect('/user/sign/in');
        });
} , (req,resp) => {
    console.log( '登录操作' );
    console.log( req.loginUser );
    // 将请求(req)中的 loginUser 添加到会话(req.session)中
    req.session.login = req.loginUser ;

    // 登录成功后，重定向到 用户列表页面
    resp.redirect('/user/list');
});

// GET `/user/list`
router.get('/user/list',(req,resp)=>{
    const session = req.session ;
    if( session.login ) {
        let sql = 'SELECT id, username, nickname FROM t_customers ORDER BY id ASC';
        pool.query( sql )
            .then( ([rows,fields]) => {
                let localeVariables = {
                    // 尝试从 会话(req.session) 中获取 已登录用户信息
                    user: session.login ,
                    users: rows
                }
                // `/views/` + `user/list` + '.njk'
                resp.render('user/list', localeVariables );
                return;
            }).catch( reason => {
                console.log( reason );
                // 这里应该去往错误页面显示错误信息的
            })
        return;
    }
    // resp.render('user/sign-in', { message: '请先登录' });
    session.message = '请先登录';
    resp.redirect('/user/sign/in');
});

// GET `/user/sign/out`
router.get('/user/sign/out',(req,resp)=>{
    // 从 会话(req.session) 中删除 login 即可
    delete req.session.login ;
    resp.redirect('/user/sign/in');
});

module.exports = router;